import json
import random
import re

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from user import models
from utils.MyRedis import myredis
from utils.SendMessage import send_message
from user import userser

from utils.tooljwt import tooljwt


# Create your views here.

class SendCodeView(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        print(phone)
        code = str(random.randint(1000, 9999))
        if re.match(r'^1[34578]\d{9}$', phone):
            # data = json.loads(send_message(phone, code, '5'))
            # if data['statusCode'] == '000000':
            #     myredis.set_time_str(phone, 60*2, code)
            #     return Response({"msg": "ok", "success": "验证码发送成功"})
            # else:
            #     return Response({"msg": "no", "error": data['statusMsg']})
            myredis.set_time_str(phone, 60 * 2, code)
            return Response({"msg": "ok", "code": code, "success": "验证码发送成功"})
        else:
            return Response({"msg": "no", "error": "手机格式不正确"})


class PhoneRegisterView(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        code = request.data.get('code')
        password = request.data.get('password')
        real_code = myredis.get_str(phone)
        print(real_code)
        if code == real_code:
            ser = userser.UserRegisterSerializer(data={'phone': phone})
            if ser.is_valid():
                models.User.objects.create(phone=phone, password=password, username=phone)
                return Response({"msg": "ok", "success": "注册成功"})
            else:
                return Response({"msg": "no", "error": ser.errors})
        else:
            return Response({"msg": "no", "error": "验证码错误"})


class EmailRegisterView(APIView):
    def post(self, request):
        email = request.data.get('email')
        password = request.data.get('password')
        ser = userser.UserRegisterSerializer(data={'email': email, 'password': password})
        if ser.is_valid():
            models.User.objects.create(username=email, email=email, password=password)
            return Response({"msg": "ok"})
        else:
            return Response({"msg": "no", "error": ser.errors})


class PhoneLoginView(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        code = request.data.get('code')
        real_code = myredis.get_str(phone)
        if code == real_code:
            user = models.User.objects.filter(phone=phone).first()
            if user:
                token = tooljwt.gettoken({"id": user.id, "username": user.username})
                print(token)
                return Response({"msg": "ok", "success": "登录成功",
                                 "data": {"userid": user.id, "username": user.username, "token": token},
                                 "type": "短信登录"})
            else:
                return Response({"msg": "phone no", "error": "用户不存在"})
        else:
            return Response({"msg": "no", "error": "验证码错误"})


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = models.User.objects.filter(username=username).first()
        if user:
            if user.password == password:
                token = tooljwt.gettoken({"id": user.id, "username": user.username})
                return Response({"msg": "ok", "success": "登录成功",
                                 "data": {"userid": user.id, "username": user.username, "token": token},
                                 "type": "密码登录"})
            else:
                return Response({"msg": "no", "error": "密码错误"})
        else:
            return Response({"msg": "no", "error": "用户名不存在"})


class UserInfoView(APIView):
    def get(self, request):
        phone = request.query_params.get('phone')
        email = request.query_params.get('email')
        if phone:
            if not re.match(r'^1[34578]\d{9}$', phone):
                return Response({"msg": "no", "error": "手机号格式不正确"})
            else:
                if models.User.objects.filter(phone=phone):
                    return Response({"msg": "ok", "success": "手机验证成功"})
                else:
                    return Response({"msg": "no", "error": "手机不存在"})
        else:
            if not re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', email):
                return Response({"msg": "no", "error": "邮箱格式不正确"})
            else:
                if models.User.objects.filter(email=email):
                    return Response({"msg": "ok", "success": "邮箱验证成功"})
                else:
                    return Response({"msg": "no", "error": "邮箱不存在"})


class UpdatePassword(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        email = request.data.get('email')
        password = request.data.get('password')
        if phone:
            models.User.objects.filter(phone=phone).update(password=password)
            return Response({"msg": "ok", "success": "修改密码成功"})
        elif email:
            models.User.objects.filter(email=email).update(password=password)
            return Response({"msg": "ok", "success": "修改密码成功"})
        else:
            return Response({"msg": "no", "error": "参数错误"})



